package ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.messageprocessors.ResponseProcessorImp;

import java.util.Date;
import java.util.concurrent.BlockingQueue;

import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.AddressType;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.AddressValue;
import net.wimpi.modbus.msg.ModbusRequest;
import net.wimpi.modbus.msg.ModbusResponse;
import net.wimpi.modbus.msg.ReadMultipleRegistersRequest;
import net.wimpi.modbus.msg.ReadMultipleRegistersResponse;
import net.wimpi.modbus.procimg.Register;

public class ReadMultipleResgistersResponseProcessor extends
		AbstractResponseProcessor {

	@Override
	public void processResponse(ModbusRequest req, ModbusResponse res, BlockingQueue<AddressValue> queue) {
		
		// TODO ReadMultipleResgistersResponseProcessor error IllegalAddressException
		
		if(res instanceof ReadMultipleRegistersResponse && req instanceof ReadMultipleRegistersRequest){
			
			Register[] regs = ((ReadMultipleRegistersResponse) res).getRegisters();
			int baseDir = ((ReadMultipleRegistersRequest) req).getReference();
			int regCount = ((ReadMultipleRegistersRequest) req).getWordCount();
			Date date = new Date();
			
			for(int i = 0; i < regCount; i++){
				
				int address = baseDir + i;
				Register value = regs[i];

				AddressValue newValue = new AddressValue();
				newValue.setAddress(address);
				newValue.setAddressType(AddressType.HOLDING_REGISTER);
				newValue.setDate(date);
				newValue.setValue(value.getValue());
				
				queue.add(newValue);
				
				getImage().setRegister(address,value,date);
				//TODO: Descomentar
				/*
				if( getDeciveDAO() != null )
						getDeciveDAO().saveValue( getDevice(), address , value.getValue() , AddressType.HOLDING_REGISTER );
				*/	
			}
			
		}
	}

}
